package com.j.lemon.learn.basic.jdkDTDL.interceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class InterceptorJdkProxy implements InvocationHandler {
    private Object target;
    private String interceptorName=null;

    public InterceptorJdkProxy(Object target, String interceptorName) {
        this.target = target;
        this.interceptorName = interceptorName;
    }

    public Object bind(Object target,String interceptorName){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new InterceptorJdkProxy(target,interceptorName));
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(interceptorName==null){
            return method.invoke(target,args);

        }
        Object result = null;
        Interceptor interceptor = (Interceptor) Class.forName(interceptorName).newInstance();
        if(interceptor.before(proxy,target,method,args)){
            result=method.invoke(target,args);
        }else{
            interceptor.around(proxy,target,method,args);
        }

        interceptor.after(proxy,target,method,args);
        return result;
    }
}
